package top.continew.admin.generator.service.impl;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vms.v20200902.VmsClient;
import com.tencentcloudapi.vms.v20200902.models.SendTtsVoiceRequest;
import com.tencentcloudapi.vms.v20200902.models.SendTtsVoiceResponse;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import top.continew.admin.config.TencentCloudTtsVoiceConfig;
import top.continew.admin.generator.service.TencentCloudTtsVoiceConfigService;

/**
 * @description:
 * @author: jiangjun
 * @date: 2025/6/20 14:41
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TencentCloudTtsVoiceConfigServiceImpl implements TencentCloudTtsVoiceConfigService {

    private final TencentCloudTtsVoiceConfig config;

    private VmsClient client;

    @PostConstruct
    public void init() {
        /* 必要步骤：
         * 实例化一个认证对象，入参需要传入腾讯云账户密钥对secretId，secretKey。
         * 这里采用的是从环境变量读取的方式，需要在环境变量中先设置这两个值。
         * 您也可以直接在代码中写死密钥对，但是小心不要将代码复制、上传或者分享给他人，
         * 以免泄露密钥对危及您的财产安全。
         * CAM密匙查询: https://console.cloud.tencent.com/cam/capi*/
        Credential cred = new Credential(config.getSecretId(), config.getSecretKey());

        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setReqMethod("POST");
        /* SDK有默认的超时时间，非必要请不要进行调整
         * 如有需要请在代码中查阅以获取最新的默认值 */
        httpProfile.setConnTimeout(60);
        httpProfile.setEndpoint(config.getEndpoint());
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setSignMethod("TC3-HMAC-SHA256");
        clientProfile.setHttpProfile(httpProfile);
        /* 实例化要请求产品(以vms为例)的client对象
         * 第二个参数是地域信息，可以直接填写字符串ap-guangzhou，或者引用预设的常量 */
        this.client = new VmsClient(cred, "ap-guangzhou", clientProfile);
    }

    @Override
    public void sendTaskNoticeVoice(String phoneNumber, Integer taskNum) throws Exception {
        SendTtsVoiceRequest req = new SendTtsVoiceRequest();
        String templateId = "4356";
        req.setTemplateId(templateId);

        // 模板参数，若模板没有参数，请提供为空数组
        String[] templateParamSet = {taskNum.toString()};
        req.setTemplateParamSet(templateParamSet);
        req.setCalledNumber(phoneNumber);
        req.setVoiceSdkAppid(config.getAppId());

        // 播放次数，可选，最多3次，默认2次
        Long playTimes = 2L;
        req.setPlayTimes(playTimes);
        SendTtsVoiceResponse res = client.SendTtsVoice(req);
        log.info("SendTtsVoiceResponse: {}", SendTtsVoiceResponse.toJsonString(res));
    }
}
